package com.guinea.core.jdbc;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.guinea.core.orm.PropertyFilter;
import com.guinea.core.utils.web.ServletUtils;

public class PropertyFilterForSql {
	String name;
	String value;
	
	public PropertyFilterForSql(String name, String value) {
		super();
		this.name = name;
		this.value = value;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	
	public static List buildFromHttpRequestForSql(final HttpServletRequest request,
			final String filterPrefix) {
		List filterList = new ArrayList();

		// 从request中获取含属性前缀名的参数,构造去除前缀名后的参数Map.
		Map filterParamMap = ServletUtils.getParametersStartingWith(request,
				filterPrefix + "_");
		
		request.setAttribute("filters",filterParamMap);
		// 分析参数Map,构造PropertyFilter列表
		for (Iterator iterator = filterParamMap.entrySet().iterator(); iterator
				.hasNext();) {
			Map.Entry entry = (Map.Entry) iterator.next();
			String filterName = (String) entry.getKey();
			String value = (String) entry.getValue();
			// 如果value值为空,则忽略此filter.
			if (StringUtils.isNotBlank(value)) {
				PropertyFilterForSql filter = new PropertyFilterForSql(filterName,value);
				filterList.add(filter);
			}
		}

		return filterList;
	}
	
	public static String getProperty(String filterName,List filters){
		String result = null;
		if(!StringUtils.isBlank(filterName) && filters != null)
		for (Iterator iter = filters.iterator(); iter.hasNext();) {
			PropertyFilterForSql p = (PropertyFilterForSql) iter.next();
			if(p != null && filterName.equals(p.getName())){
				result = p.getValue();
			}
		}
		return result;
	}
	
}
